<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="renderer" content="webkit|ie-comp|ie-stand">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <title>设备信息</title>
</head>

<body>
  <div id="app" v-loading.fullscreen.lock="loading">
    <div class="equipment-info">
      <search-btn-view btn-text="设备查询" @search="searchData">
        <template slot="append">
          <el-button @click="addEquipment" size="medium" type="primary">添加设备</el-button>
        </template>
        <div slot="search-content">
          <search-form :search="search" :equipments="equipmentList" :dept-workshop-list="deptWorkshopList"></search-form>
        </div>
      </search-btn-view>
      <div v-if="totalPrice!==null" style="margin-bottom:5px;">
        <span>总价:{{totalPrice}}</span>
      </div>
      <div class="equipment-info-table-div">
        <el-table fit stripe border ref="equipmentTable" :data="pageEquipmentList" style="width:100%" height="parent">
          <el-table-column prop="equipmentNo" label="设备编号" min-width="120px" header-align="center"></el-table-column>
          <el-table-column prop="equipmentName" label="设备名称" min-width="100px" header-align="center"></el-table-column>
          <el-table-column prop="manufacturer" label="生产厂家" min-width="100px" header-align="center"></el-table-column>
          <el-table-column prop="purchasePrice" label="采购单价" min-width="100px" align="center"></el-table-column>
          <el-table-column :resizable="false" label="采购日期" width="85px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.purchaseTime!==''">
                {{moment(scope.row.purchaseTime).format('YYYY-MM-DD')}}
              </span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" prop="dailyWorkingHours" label="日工作时长" width="85px" align="center">
            <template slot-scope="scope">
              <span>{{getTimeStr(scope.row.dailyWorkingHours)}}</span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="设备图片" width="90px" align="center">
            <template slot-scope="scope">
              <el-image class="equipment-img" v-if="scope.row.equipmentImage" :src="formatImgUrl(scope.row.equipmentImage)"
                fit="scale-down">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="部门-车间" min-width="120px" header-align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.depWork!==null">{{scope.row.depWork.deptName}} - {{scope.row.depWork.workshopName}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="deviceType" label="设备类型" min-width="120px" header-align="center"></el-table-column>
          <el-table-column prop="upperComputer" label="上位机" min-width="120px" header-align="center"></el-table-column>
          <el-table-column prop="energyNo" label="使用电表" min-width="120px" header-align="center"></el-table-column>
          <el-table-column prop="flowNo" label="使用气表" min-width="120px" header-align="center"></el-table-column>
          <el-table-column :resizable="false" label="操作" align="center" width="130px" fixed="right">
            <template slot-scope="scope">
              <div>
                <el-button size="mini" type="primary" @click="updateEquipment(scope.row)">修改</el-button>
                <el-button size="mini" type="danger" @click="deleteEquipment(scope.row)">删除</el-button>
              </div>
              <div style="margin-top:3px" v-if="scope.row.internetThingsCard!==''">
                <el-button size="mini" type="primary" @click="createQrcode(scope.row)">物联网卡二维码</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="margin-top:5px;text-align:right;" v-if="pagination.totalCount!==0">
        <el-pagination background :page-size="pagination.pageSize" :total="pagination.totalCount" :current-page.sync="pagination.currentPage"
          @current-change="pageChange"></el-pagination>
      </div>

      <el-dialog :title="formType==='add'?'添加设备':'修改设备'" :visible.sync="openFormDialog" top="10vh" width="60%" custom-class="formDialog"
        :close-on-click-modal="false" @closed="formDialogClosed">
        <div style="height:calc(80vh - 54px);overflow:auto">
          <equipment-form v-if="openFormDialog" :equipment="selectEquipment" :type="formType" :dropdown-option="dropdownOption"
            @save-success="saveSuccess"></equipment-form>
        </div>
      </el-dialog>

      <el-dialog title="物联网卡二维码" :visible.sync="openQrCode" top="calc(50vh - 160px)" @closed="qcodeClosed">
        <div>
          <card-code v-if="openQrCode" :card="selectEquipment"></card-code>
        </div>
      </el-dialog>
    </div>
  </div>
</body>

<script src="https://upload.shinehao.com.cn/20181222140744qiniu.min.js"></script>
<script src="../../myJs/importFile.js"></script>
<script>
  importFile([
    "/vueSystem/components/css/sysCommonSearch.css",
    "/vueSystem/components/css/searchBtnView.css",
    "/vueSystem/components/css/timeDurationInput.css",
    "/vueSystem/components/css/imgUpload.css",
    "/remoteEquipment/cardSetting/css/cardCode.css",
    "./css/workTimeSetting.css",
    "./css/workProcedureSetting.css",
    "./css/equipmentForm.css",
  ], [
    "/static/vue/qrcode.min.js",
    "/vueSystem/i18n/index.js",
    "/vueSystem/components/sysCommonSearch.js",
    "/vueSystem/components/searchBtnView.js",
    "/vueSystem/models/baseModel.js",
    "/vueSystem/js/checkVaildUtil.js",
    "/vueSystem/components/timeDurationInput.js",
    "/vueSystem/components/imgUpload.js",
    "/vueSystem/components/TimeRangePicker.js",
    "/remoteEquipment/cardSetting/cardCode.js"
  ]);

</script>
<script src="../utils/moduleUtil.js"></script>
<script src="../models/equipmentFormModel.js"></script>
<script src="./searchForm.js"></script>
<script src="./workTimeSetting.js"></script>
<script src="./workProcedureSetting.js"></script>
<script src="./equipmentForm.js"></script>

<script>
  var app = new Vue({
    el: '#app',
    data: function () {
      var search = {
        deptWorkshop: [],
        equipmentNo: '',
        manufacturer: '',
        showInBoard: '',
        internetThingsCard: '',
        upperComputer: '',
        deviceType: '',
        energyNo: '',
        flowNo: ''
      };

      return {
        loading: false,
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        deptWorkshopList: [],
        deptWorkshopMap: null,
        equipmentList: [],
        searchEquipmentList: [],
        pageEquipmentList: [],
        totalPrice: null,
        dropdownOption: {},
        openFormDialog: false,
        openQrCode: false,
        formType: '',
        selectEquipment: null,
        pagination: {
          currentPage: 1,
          totalCount: 0,
          pageSize: 10
        },
        moment: moment
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      this.setDeptWorkshopList().then(function () {
        return self.setData(true).then(function () {
          self.loading = false;
        });
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      setDeptWorkshopList: function () {
        var self = this;
        return ModuleUtil.getDepAndWorkShop().then(function (deptWorkshopList) {
          var deptWorkshopMap = {};
          for (var i = 0; i < deptWorkshopList.length; i++) {
            var dept = deptWorkshopList[i];
            var workshops = dept.workshops;
            for (var j = 0; j < workshops.length; j++) {
              var workshop = workshops[j];
              deptWorkshopMap[workshop.value] = {
                deptId: dept.value,
                deptName: dept.label,
                workshopId: workshop.value,
                workshopName: workshop.label
              };
            }
          }

          self.deptWorkshopMap = deptWorkshopMap;
          self.deptWorkshopList = deptWorkshopList;
          return deptWorkshopList;
        });
      },

      setData: function (isSearch) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        }

        var search = this.search;
        var postData = {};

        var deptWorkshop = search.deptWorkshop;
        var dept = deptWorkshop[0];
        if (dept !== undefined) {
          postData.department = dept;
        }

        var workshop = deptWorkshop[1];
        if (workshop !== undefined) {
          postData.workShop = workshop;
        }

        var self = this;
        return ajaxRequest('equipment/getAllEquipment', postData).then(function (res) {
          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);
          }
          var equipmentList = res.returnData;
          for (var i = 0; i < equipmentList.length; i++) {
            var equipment = equipmentList[i];
            self.formatData(equipment);
          }

          self.equipmentList = equipmentList;
          self.toSearchEquipmentList();
          return equipmentList;
        });
      },

      calTotalPrice: function () {
        var equipmentList = this.searchEquipmentList;
        var totalPrice = _.sumBy(equipmentList, 'purchasePrice');
        totalPrice = _.round(totalPrice, 2);
        this.totalPrice = totalPrice;
      },

      toSearchEquipmentList: function () {
        var search = this.search;
        var equipmentList = this.equipmentList;
        var fields = ['equipmentNo', 'manufacturer', 'internetThingsCard', 'upperComputer', 'deviceType', 'energyNo', 'flowNo'];
        equipmentList = _.filter(equipmentList, function (equipment) {
          var showInBoard = search.showInBoard;
          if (showInBoard !== '') {
            if (showInBoard !== equipment.showInBoard) {
              return false;
            }
          }
          for (var i = 0; i < fields.length; i++) {
            var field = fields[i];
            var searchValue = search[field];
            if (searchValue === '') {
              continue;
            }
            var value = equipment[field];
            if (SysUtil.isEmpty(value)) {
              return false;
            }

            searchValue = searchValue.toLowerCase();
            value = value.toLowerCase();
            if (value.indexOf(searchValue) === -1) {
              return false;
            }
          }
          return true;
        });
        this.searchEquipmentList = equipmentList;
        this.pagination.totalCount = equipmentList.length;
        this.calTotalPrice();
        this.toPageEquipmentList();
      },

      toPageEquipmentList: function () {
        var pagination = this.pagination;
        var pageSize = pagination.pageSize;
        var totalPage = Math.ceil(pagination.totalCount / pageSize);
        var currentPage = Math.min(pagination.currentPage, totalPage);
        var startIndex = (currentPage - 1) * pageSize;

        var equipmentList = this.searchEquipmentList;
        equipmentList = equipmentList.slice(startIndex, startIndex + pageSize);
        this.pageEquipmentList = equipmentList;
      },

      resetData: function (isSearch) {
        this.loading = true;
        var self = this;
        this.setData(isSearch).then(function () {
          self.loading = false;
        });
      },

      formatData: function (equipment) {
        equipment.purchaseTime = SysUtil.formatString2Date(equipment.purchaseTime);
        equipment.depreciableLife = SysUtil.formatString2Date(equipment.depreciableLife);

        if (SysUtil.isEmpty(equipment.equipmentImage)) {
          equipment.equipmentImage = '';
        }

        var deptWorkshopMap = this.deptWorkshopMap;
        var workshopId = equipment.workShop;
        var deptWorkshop = deptWorkshopMap[workshopId];
        if (deptWorkshop !== undefined) {
          equipment.depWork = _.cloneDeep(deptWorkshop);
        } else {
          equipment.depWork = null;
        }

        var numberFields = ['dailyWorkingHours', 'timeoutBreakElectricityTime',
          'timeoutBreakFlowTime'
        ];
        for (var i = 0; i < numberFields.length; i++) {
          var numberField = numberFields[i];
          var value = equipment[numberField];
          if (value === 0) {
            equipment[numberField] = null;
          }
        }
      },

      searchData: function () {
        this.pagination.currentPage = 1;
        var search = this.search;
        var oldSearch = this.oldSearch;
        if (!SysUtil.equalsArray(search.deptWorkshop, oldSearch.deptWorkshop, true)) {
          this.resetData(true);
          return;
        }

        this.toSearchEquipmentList();
        this.oldSearch = _.cloneDeep(this.search);
      },

      pageChange: function () {
        this.search = _.cloneDeep(this.oldSearch);
        this.toPageEquipmentList();
      },

      addEquipment: function () {
        this.selectEquipment = null;
        this.formType = 'add';
        this.openFormDialog = true;
      },

      updateEquipment: function (equipment) {
        this.selectEquipment = equipment;
        this.formType = 'update';
        this.openFormDialog = true;
      },

      saveSuccess: function () {
        this.openFormDialog = false;
        this.resetData();
      },

      formDialogClosed: function () {
        this.selectEquipment = null;
        this.formType = '';
      },

      deleteEquipment: function (equipment) {
        var self = this;
        this.$confirm(`确认是否删除\`${equipment.equipmentName}\`名称的设备`, '删除确认').then(function () {
          self.toDeleteEquipment(equipment);
        }).catch(function () {});
      },

      toDeleteEquipment: function (equipment) {
        this.loading = true;
        var self = this;
        ajaxRequest('equipment/delEquipment', {
          id: equipment.id
        }).then(function () {
          self.loading = false;
          self.$alert('设备删除成功', '信息', {
            callback: function () {
              var equipmentList = self.equipmentList;
              if (equipmentList.length === 1) {
                var pagination = self.pagination;
                if (pagination.currentPage !== 1) {
                  pagination.currentPage -= 1;
                }
              }
              self.setData();
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      getTimeStr: function (time) {
        if (SysUtil.isEmpty(time) || time === 0) {
          return '';
        }

        var timeDuration = moment.duration({
          hours: time
        });
        var str = '';
        var hour = timeDuration.hours();
        if (hour !== 0) {
          str += `${hour}小时`;
        }

        var minute = timeDuration.minutes();
        if (minute !== 0) {
          str += `${minute}分`;
        }
        return str;
      },

      createQrcode: function (equipment) {
        this.selectEquipment = equipment;
        this.openQrCode = true;
      },

      qcodeClosed: function () {
        this.selectEquipment = null;
      }
    },

    components: {
      SearchBtnView: SearchBtnView,
      SearchForm: SearchForm,
      EquipmentForm: EquipmentForm,
      CardCode: CardCode
    }
  });

</script>

<style>
  .equipment-info {
    padding: 10px 20px;
    height: calc(100% - 15px);
    padding-bottom: 5px;
    overflow: auto;
    min-width: 500px;
    display: flex;
    flex-direction: column;
  }

  .equipment-info .search-div {
    margin-bottom: 5px;
  }

  .equipment-info .search-div>div {
    float: left;
    margin-right: 10px;
    line-height: 36px;
  }

  .equipment-info .search-div>div:last-child {
    margin-right: 0;
  }

  .equipment-info .equipment-info-table-div {
    flex: 1;
    overflow: auto;
  }

  .equipment-info .equipment-info-table-div .equipment-img {
    width: 80px;
    height: 80px;
  }

  .equipment-info .formDialog {
    min-width: 400px;
    min-height: 200px;
  }

  .equipment-info .equipment-info-table-div .el-button+.el-button {
    margin-left: 5px;
  }

  .search-form .search-input {
    width: 180px;
  }

</style>

</html>
